# -*- coding: utf-8 -*-
# @Time    : 2019/2/20 10:50 AM
# @Author  : yuhuan
# @Email   : yuhuan@imeijian.cn
# @File    : gitLabWebhooks.py
# @Software: PyCharm
# @ProjectName: DownLoadData
# @FileDesc: 
#

# pip install web.py json requests
# -----------------------------------------------------

import sys
import logging
import web
import json
import requests

reload(sys)
sys.setdefaultencoding("utf-8")

LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
# logging.basicConfig(filename='my.log', level=logging.INFO, format=LOG_FORMAT)
logging.basicConfig(filename='log/master.log', level=logging.INFO, format=LOG_FORMAT)

urls = (
    '/robot/send', 'sendDD'
)
app = web.application(urls, globals())


class sendDD:

    def POST(self):

        input_body = json.loads(web.data())

        if input_body['ref'] == 'refs/heads/master':

            url = "https://oapi.dingtalk.com/robot/send"
            querystring = {"access_token": web.input()["access_token"]}
            headers = {'Content-Type': "application/json;charset=utf-8"}

            response = requests.request("POST", url, data=web.data(), headers=headers, params=querystring)

            logging.info('%s pushed to branch master at repository [%s], total_commits_count=%s'
                         % (input_body['user_name'], input_body['repository']['name'], input_body['total_commits_count']))
            logging.info(response)

            return json.dumps({
                'c': 0,
                'm': '转发完成'
            })
        else:
            return json.dumps({
                'c': 1,
                'm': '参数无效'
            })


if __name__ == "__main__":
    app.run()
